package problems.daily.y2021m7;

/**
 * @author habitplus
 * @since 2021-07-14 15:58
 */
public class T20210714N2 {
    // 189. 旋转数组
    // 给定一个数组，将数组中的元素向右移动 k 个位置，其中 k 是非负数。
    // 提示：
    //      1 <= nums.length <= 2 * 104
    //      -231 <= nums[i] <= 231 - 1
    //      0 <= k <= 105
    // 链接：https://leetcode-cn.com/problems/rotate-array/
    /** 翻转三次 **/
    public void rotate(int[] nums, int k) {
        k %= nums.length;
        reverse(nums, 0, nums.length - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, nums.length - 1);
    }

    private void reverse(int[] nums, int start, int end) {
        while (start < end) {
            int temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
            start += 1;
            end -= 1;
        }
    }

    /** 环状替换 **/
    public void rotate01(int[] nums, int k) {
        int n = nums.length;
        k = k % n;
        int count = gcd(k, n);
        for (int start = 0; start < count; ++start) {
            int current = start;
            int prev = nums[start];
            do {
                int next = (current + k) % n;
                int temp = nums[next];
                nums[next] = prev;
                prev = temp;
                current = next;
            } while (start != current);
        }
    }

    private int gcd(int x, int y) {
        return y > 0 ? gcd(y, x % y) : x;
    }
}
